package com.groupbaby.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.groupbaby.ydd.common.BusinessException;
import com.groupbaby.ydd.common.ResultData;
import com.groupbaby.ydd.dto.SysRoleDto;
import com.groupbaby.ydd.dto.SysPageDto;
import com.groupbaby.ydd.entity.SysMenu;
import com.groupbaby.ydd.entity.SysRole;

import com.groupbaby.ydd.entity.SysRoleMenu;
import com.groupbaby.ydd.entity.SysUser;
import com.groupbaby.ydd.service.ISysMenuService;
import com.groupbaby.ydd.service.ISysRoleMenuService;
import com.groupbaby.ydd.service.ISysRoleService;
import com.groupbaby.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author ydg
 * @since 2022-10-10
 */
@RestController
@RequestMapping("/sys_role")
@Slf4j
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysRoleMenuService roleMenuService;
    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页查询
     *
     * @param page  页面
     * @param limit 限制
     * @param name  名字
     * @return {@link ResultData}
     */

    @GetMapping("/list")
    public ResultData page(int page, int limit, String name) {
        //构造分页构造器
        Page<SysRole> pageInfo = new Page(page, limit);
        //条件构造器
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper();
        //按姓名查询
        queryWrapper.like(StringUtils.isNotEmpty(name), SysRole::getName, name);
        //添加排序条件,按id
        queryWrapper.orderByDesc(SysRole::getId);
        //执行查询
        sysRoleService.page(pageInfo, queryWrapper);
        SysPageDto pageDto = new SysPageDto();
        pageDto.setCount(pageInfo.getTotal());//设置总数
        pageDto.setTotalPages(pageInfo.getPages());//设置总页数
        pageDto.setPageSize(limit);//设置每页条数
        pageDto.setCurrentPage(page);//设置当前页
        //设置当前页集合
        pageDto.setData(pageInfo.getRecords());

        return ResultData.ok("查询成功", pageDto);
    }


    /**
     * 修改的数据回显功能
     *
     * @param
     * @return {@link ResultData}
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(SysRole sysRole) {

        //获取sys_role的角色
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getId, sysRole.getId());
        SysRole sysRole1 = sysRoleService.getOne(wrapper);

        SysRoleDto sysRoleDto = new SysRoleDto();
        BeanUtils.copyProperties(sysRole1, sysRoleDto);

        //获取角色id对应的菜单id集合
        LambdaQueryWrapper<SysRoleMenu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysRoleMenu::getRoleId, sysRole.getId());
        List<SysRoleMenu> sysRoleMenus = roleMenuService.list(wrapper1);

        //遍历集合,获取一级菜单和其子菜单
        List<SysMenu> sysMenus = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenus) {

            LambdaQueryWrapper<SysMenu> wrapper2 = new LambdaQueryWrapper<>();
            //只要一级菜单
            wrapper2.eq(SysMenu::getPid, 0);
            wrapper2.eq(SysMenu::getId, sysRoleMenu.getMenuId());

            SysMenu sysMenu = sysMenuService.getOne(wrapper2);

           //获取子菜单
            if (sysMenu != null) {
                sysMenu = sysMenuService.getUseChildren(sysMenu, sysRoleMenus);
                sysMenus.add(sysMenu);
            }
        }

        sysRoleDto.setAuthList(sysMenus);
        return ResultData.ok("", sysRoleDto);

    }

  /*  @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        //思路:根据角色id查询对应的菜单id,再而根据菜单id查询菜单数据
        //返回:角色名称,角色描述,角色权限

        //根据Id查询管理员信息
        SysRole role = sysRoleService.getById(id);
        //复制到menu1dto
        Menu1Dto menu1Dto = new Menu1Dto();
        BeanUtils.copyProperties(role, menu1Dto, "authList");

        //根据角色id查询对应的一级菜单id
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, id);
        List<SysRoleMenu> list = roleMenuService.list(queryWrapper);
        //ids存放了对应用户的菜单id
        List<String> ids = list.stream().map(item -> {
            String menuId = item.getMenuId();
            return menuId;
        }).collect(Collectors.toList());

        //而根据一级菜单id查询一级菜单数据对象
        LambdaQueryWrapper<SysMenu> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SysMenu::getPid, 0);
        queryWrapper1.in(SysMenu::getId, ids);
        List<SysMenu> list1 = sysMenuService.list(queryWrapper1);
        //把对象复制给dto类
        List<Menu1Dto> menu1DtoList = new ArrayList();
        for (int i = 0; i <list1.size() ; i++) {
            Menu1Dto menu1=new Menu1Dto();
            BeanUtils.copyProperties(list1.get(i),menu1);
            menu1DtoList.add(menu1);
        }
        //根据一级菜单的id,去查二级菜单的pid,然后找到二级菜单的对象集合
        List<SysMenu> list2 = null;
        for (int i = 0; i < list1.size(); i++) {
            SysMenu sysMenu = list1.get(i);
            Integer id1 = sysMenu.getId();
            LambdaQueryWrapper<SysMenu> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(SysMenu::getPid, sysMenu.getId());
            //这是二级菜单的对象集合
            sysMenuService.list(queryWrapper2);
        }
        //把对象复制给2dto类
        List<Menu2Dto> menu1DtoList2 = new ArrayList();
        for (int i = 0; i <list2.size() ; i++) {
            Menu2Dto menu2=new Menu2Dto();
            BeanUtils.copyProperties(list1.get(i),menu2);
            menu1DtoList2.add(menu2);
        }
        //根据二级菜单的id,去查三级菜单的pid,然后找到三级菜单的对象集合
        List<SysMenu> list3 = null;
        for (int j = 0; j < list2.size(); j++) {
            SysMenu sysMenu2 = list2.get(j);
            Integer id2 = sysMenu2.getId();
            LambdaQueryWrapper<SysMenu> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(SysMenu::getPid, sysMenu2.getId());
            //这是三级菜单的对象集合
            sysMenuService.list(queryWrapper3);
        }
        return null;
    }*/

    @PostMapping("/update")
    public ResultData update(@RequestBody SysRoleDto sysRoleDto) {
        //修改数据
        sysRoleService.updateById(sysRoleDto);
        //注意角色表关联了权限表,权限表中的数据也要修改
        //删除role_menu表中对应数据
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        Integer[] menuIds = sysRoleDto.getMenuIds();

        String roleId = sysRoleDto.getId();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        roleMenuService.remove(wrapper);

        //重新保存
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Integer menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);//角色编号
            sysRoleMenu.setMenuId(menuId + "");//菜单编号
            sysRoleMenus.add(sysRoleMenu);
        }

        roleMenuService.saveBatch(sysRoleMenus);
        return ResultData.ok("修改成功", sysRoleDto);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @GetMapping("/allData")
    public ResultData getAllData() {

        List<SysRole> sysRoles = sysRoleService.list();

        return ResultData.ok("ok", sysRoles);

    }

    /**
     * 新增数据
     *
     * @param sysRoleDto
     * @return
     */
    @PostMapping("/add")
    public ResultData save(@RequestBody SysRoleDto sysRoleDto) {

        //保存到role表中
        SysRole sysRole=new SysRole();
        sysRole.setDescription(sysRoleDto.getDescription());
        sysRole.setName(sysRoleDto.getName());
        //将保存到sys_role表
        sysRoleService.save(sysRole);

        //将拥有的权限保存到sys_role_menu表中
        Integer[] menuIds = sysRoleDto.getMenuIds();
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Integer menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            //sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId + "");
            sysRoleMenus.add(sysRoleMenu);
        }
        roleMenuService.saveBatch(sysRoleMenus);
return  ResultData.ok("",sysRoleDto);
    }

    @GetMapping("/del")
    public ResultData delete(SysRoleDto sysRoleDto) {
        //超级管理员不能删
        SysRole sysRole = sysRoleService.getById(sysRoleDto.getId());
        if (sysRole.getSuperadmin() == 1) {
            throw new BusinessException("超级管理员不能删!");
        }
        //角色表关联了管理的用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getRoleId, sysRoleDto.getId());
        int count = sysUserService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("该角色下有用户,无法删除!");
        }
        //删除角色数据
        sysRoleService.removeById(sysRoleDto.getId());
        //删除对应的权限数据
        LambdaQueryWrapper<SysRoleMenu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysRoleMenu::getRoleId, sysRoleDto.getId());
        roleMenuService.remove(wrapper1);
        return ResultData.ok("删除成功", sysRoleDto);
    }
}
